package hello.app;

import hello.app.model.HelloSetting.DataType;
import hello.app.util.Debug;
import hello.app.util.ThreadUtil;
import hello.app.util.ThreadUtil.Runner;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.os.Handler;
import android.preference.Preference;
import android.preference.PreferenceCategory;
import android.preference.PreferenceScreen;
import android.preference.Preference.OnPreferenceClickListener;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Toast;
import billing.app.BillingService;
import billing.app.Consts;
import billing.app.PurchaseObserver;
import billing.app.ResponseHandler;
import billing.app.BillingService.RequestPurchase;
import billing.app.BillingService.RestoreTransactions;
import billing.app.Consts.PurchaseState;
import billing.app.Consts.ResponseCode;

/**
 * 設定画面+アップグレード
 * @author taketo
 *
 */
public class SettingPlusActivity extends SettingActivity implements OnPreferenceClickListener{

	private static final int DIALOG_BILLING_NOT_SUPPORTED_ID = 2;
	private static final int DIALOG_ONLY_SUPER_USER_GOOGLE = 4;
	private static final int DIALOG_ONLY_SUPER_USER_HOSTORY = 5;

	private BillingService mBillingService;
	private HelloPurchaseObserver mHelloPurchaseObserver;
	private Handler mHandler;


	public static void start(Context context){
		context.startActivity(new Intent(context,SettingPlusActivity.class));
	}

	public static void startWithUpgrade(Context context){
		Intent in = new Intent(context,SettingPlusActivity.class);
		in.putExtra("upgrade", true);
		context.startActivity(in);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		if(!mSetting.isSuperUser()){
			mHandler = new Handler();
			mHelloPurchaseObserver = new HelloPurchaseObserver(mHandler);
			mBillingService = new BillingService();
			mBillingService.setContext(this);

			ResponseHandler.register(mHelloPurchaseObserver);
			if (!mBillingService.checkBillingSupported()) {
				Debug.log("Error Billing Service");
			}
		}
		PreferenceCategory category = (PreferenceCategory) findPreference(getString(R.string.hello_settig_category));
		PreferenceScreen uprgade = getPreferenceManager().createPreferenceScreen(this);
		uprgade.setKey(getString(R.string.upgrade));
		uprgade.setTitle(R.string.upgrade_title);
		category.addPreference(uprgade);
		uprgade.setOnPreferenceClickListener(this);

		Bundle extras = getIntent().getExtras();
		if(extras != null){
			Boolean upgrade = extras.containsKey("upgrade") ? (Boolean)extras.getSerializable("upgrade") : false;
			if(upgrade != null && upgrade == true && !mSetting.isSuperUser()){
				if (!mBillingService.requestPurchase(Application.UPGRADE_ITEMEX_ID, "")) {
						showDialog(DIALOG_BILLING_NOT_SUPPORTED_ID);
				}
			}
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		mBillingService.unbind();
	}

	@Override
	protected void onStart() {
		super.onStart();
		ResponseHandler.register(mHelloPurchaseObserver);
	}

	@Override
	protected void onStop() {
		super.onStop();
		ResponseHandler.unregister(mHelloPurchaseObserver);
	}

	private Dialog createSampleDialog(String title, int resourceId){
		LayoutInflater factory = LayoutInflater.from(this);
        final View inputView = factory.inflate(resourceId, null);
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(title).setIcon(android.R.drawable.stat_sys_warning);
		builder.setView(inputView).setPositiveButton("キャンセル", null)
		.setNegativeButton("アップグレード", new OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				if (!mSetting.isSuperUser()) {
					if (!mBillingService.requestPurchase(Application.UPGRADE_ITEMEX_ID, "")) {
						showDialog(DIALOG_BILLING_NOT_SUPPORTED_ID);
					}
				}
				dialog.cancel();
			}
		});
		return builder.create();
	}

	public boolean onPreferenceClick(Preference preference) {
		if(isEqualKey(preference, getString(R.string.upgrade))){
			if (!mSetting.isSuperUser()) {
				if (!mBillingService.requestPurchase(Application.UPGRADE_ITEMEX_ID, "")) {
					showDialog(DIALOG_BILLING_NOT_SUPPORTED_ID);
				}
			}
		}
		return false;
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DIALOG_BILLING_NOT_SUPPORTED_ID:
			return createDialog(Application.TITLE, "お使いの機種はアップグレードに対応していません");
		case DIALOG_ONLY_SUPER_USER_GOOGLE:
			return createSampleDialog(Application.TITLE, R.layout.sample_google_dialog);
		case DIALOG_ONLY_SUPER_USER_HOSTORY:
			return createSampleDialog(Application.TITLE, R.layout.sample_history_dialog);
		default:
			return super.onCreateDialog(id);
		}
	}

	private void changeSuperUser(){
		mSetting.write(DataType.SUPER_USER, true);
		ThreadUtil thread = new ThreadUtil(new Runner() {
			public void exec(Object... args) {
				try {
					mApi.changeSuperUser();
				} catch (Exception e){
				}
			}
		});
		thread.start();
	}

	private class HelloPurchaseObserver extends PurchaseObserver {
		public HelloPurchaseObserver(Handler handler) {
			super(SettingPlusActivity.this, handler);
		}

		@Override
		public void onBillingSupported(boolean supported) {
			if (Consts.DEBUG) {
				Debug.log("supported: " + supported);
			}
			if (supported) {

			} else {

			}
		}

		@Override
		public void onPurchaseStateChange(PurchaseState purchaseState,
				String itemId, int quantity, long purchaseTime,
				String developerPayload) {
			Toast t = Toast.makeText(SettingPlusActivity.this, "アップグレードが完了しました", Toast.LENGTH_LONG);
			t.show();
			if(!mSetting.isSuperUser()){
				changeSuperUser();
				finish();
			}
			return;
		}

		@Override
		public void onRequestPurchaseResponse(RequestPurchase request,
				ResponseCode responseCode) {
			if (responseCode == ResponseCode.RESULT_OK) {
				changeSuperUser();
				finish();
			}else if(responseCode == ResponseCode.RESULT_ERROR ||
						responseCode == ResponseCode.RESULT_ITEM_UNAVAILABLE){
				//showDialog(DIALOG_UNKOWN_ERROR);
			}
			return;
		}

		@Override
		public void onRestoreTransactionsResponse(RestoreTransactions request,
				ResponseCode responseCode) {

			if (responseCode == ResponseCode.RESULT_OK) {

			} else {

			}
			return;
		}
	}
}
